package com.baayso.demo.sj.blog;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.baayso.demo.sj.common.ModelInjector;
import com.baayso.demo.sj.utils.ValidateUtils;

@Controller
@RequestMapping("/blog")
public class BlogController {

    @RequestMapping("/list")
    public String list(@ModelAttribute("pageNumber") String pageNumber, ModelMap modelMap) {
        int pageNumberInt = ValidateUtils.isUnsignedInt(pageNumber) ? Integer.parseUnsignedInt(pageNumber) : 1;

        modelMap.addAttribute("blogPage", Blog.me.paginate(pageNumberInt, 10));

        return "blog/list";
    }

    @RequestMapping("/addUI")
    public String addUI() {
        return "blog/add";
    }

    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        Blog blog = (Blog) ModelInjector.inject(Blog.class, request, false);
        blog.save();

        return "redirect:list";
    }

    @RequestMapping("/editUI/{id}")
    public String editUI(@PathVariable String id, ModelMap modelMap) {
        modelMap.addAttribute("blog", Blog.me.findById(Integer.parseInt(id)));

        return "blog/edit";
    }

    @RequestMapping("/edit")
    public String edit(HttpServletRequest request) {
        Blog blog = (Blog) ModelInjector.inject(Blog.class, request, false);
        blog.update();

        return "redirect:list";
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable String id) {
        Blog.me.deleteById(Integer.parseInt(id));

        return "redirect:/blog/list";
    }

}
